package com.conph.rpc.core;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class RpcServer implements Runnable {
	private ServerSocket server;
	private int port;
	private volatile boolean goon;
	private final RpcBeanFactory rpcBeanFactory;
	private static long executorId;
	
	public RpcServer() {
		rpcBeanFactory = new RpcBeanFactory();
		goon = false;
	}

	public void setPort(int port) {
		this.port = port;
	}
	
	RpcBeanFactory getRpcBeanFactory() {
		return rpcBeanFactory;
	}
	
	// TODO 注解扫描注册RPC方法
	
	public void registryRpc(Class<?> interfaces, Object object) {
		RpcBeanRegistry.registInterface(rpcBeanFactory, interfaces, object);
	}

	public void registryRpc(Class<?> interfaces, Class<?> implementsClass) {
		RpcBeanRegistry.registInterface(rpcBeanFactory, interfaces, implementsClass);
	}
	
	public void startRpcServer() throws Exception {
		if (this.port == 0) {
			// TODO 抛异常
			return;
		}
		this.server = new ServerSocket(port);
		this.goon = true;
		System.out.println("ServerIp: "  + this.server);
		new Thread(this, "RPC_SERVER").start();
	}
	
	public void stopRpcServer() {
		if (this.server != null && !this.server.isClosed()) {
			try {
				this.server.close();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				this.server = null;
			}
		}
	}

	@Override
	public void run() {
		while (goon) {
			try {
				Socket rpcClient = server.accept();
				new RpcServerExecutor(this, rpcClient, ++executorId);
			} catch (Exception e) {
				goon = false;
			}
		}
		stopRpcServer();
	}
	
}
